

#include "board_ppm.h"



volatile uint16_t IC4ReadValue1 = 0, IC4ReadValue2 = 0;
volatile uint32_t Capture = 0;
volatile uint32_t Duty    = 0;

volatile uint32_t ch[MAX_PPM_CHANNEL];

/**
  * @brief  This function handles TIM4 global interrupt request.
  * @param  None
  * @retval None
  */
void TIM4_IRQHandler(void)
{
  volatile static  int32_t c_overflow=0;
  volatile static uint32_t over_flag=0,flag = 0,tmp0=345,tmp1=765,tmp2=654;
  volatile static uint32_t ch_counter=0;
  /* Temp variable for volatile. */
  uint32_t v_i,v_k;

  if(TIM_GetITStatus(TIM4, TIM_IT_Update) == SET)
  {
    /* Clear TIM3 Capture compare interrupt pending bit */
    TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
    /* OverfloW counter. */
    c_overflow++;
    /* Set flag if overflow. */
    over_flag=1;
  }
  if(TIM_GetITStatus(TIM4, TIM_IT_CC1) == SET)
  {
    TIM_ClearITPendingBit(TIM4, TIM_IT_CC1);
  }
  if(TIM_GetITStatus(TIM4, TIM_IT_CC2) == SET)
  {
    TIM_ClearITPendingBit(TIM4, TIM_IT_CC2);
    /* Get capture value. */
    IC4ReadValue2 = TIM_GetCapture2(TIM4);

   /* Capture computation */
   /*
    * If was overflow and capture more that 45000
    * it looks like overflow happend after capture interrupt
    * and we do not need account for last overflow.
    */
    if(over_flag == 1)
    {
      if(IC4ReadValue2 > 45000)
      {
        c_overflow--;
      }
    }
    /* Calculate differences. */
    //Capture = ((0xFFFF*c_overflow - IC4ReadValue1) + IC4ReadValue2);
    v_i = IC4ReadValue1;
    v_k = IC4ReadValue2;
    Capture = 0xFFFF * c_overflow - v_i + v_k ;

    /* Time filter. If differences less than 800, lets wait next synchro pulse. */
    if((Capture/SysClkMHz)<800)
    {
      flag=0;
      ch[MAX_PPM_CHANNEL-1]++;
    }
    /* Check for synchro pulse. */
    if(Capture > PPM_SYNCHRO_TIME)
    {
      ch_counter=0;
      flag =1;
    }
    else
    {
      if(flag == 1)
      {

        //ch[ch_counter]=Capture;
        v_i = Capture;
        ch[ch_counter]=v_i;
        ch_counter++;
        if(ch_counter >= MAX_PPM_CHANNEL)
        {
          ch_counter = MAX_PPM_CHANNEL-1;
        }
      }
    }
    c_overflow=0;
    IC4ReadValue1 = IC4ReadValue2;
  }
  if(TIM_GetITStatus(TIM4, TIM_IT_CC3) == SET)
  {
    TIM_ClearITPendingBit(TIM4, TIM_IT_CC3);
  }
  if(TIM_GetITStatus(TIM4, TIM_IT_CC4) == SET)
  {
    TIM_ClearITPendingBit(TIM4, TIM_IT_CC4);
  }
  over_flag=0;
}

/**
  * @brief  This function get value of each PPM channel.
  * @param  ch_number:
  *     @arg 0-(MAX_PPM_CHANNEL-1)
  * @retval Channel value in microSeconds
  */
uint32_t get_ppm_channel_value(uint32_t ch_number)
{
  if(ch_number < MAX_PPM_CHANNEL)
  {
    return((ch[ch_number])/SysClkMHz);
  }
  else
  {
    while(1){};
  }
}






